<template>
    <div class="psd-viewer-root">
        <div  class="img-wrapper"
             ref="imgWrapper"
             v-loading="loading"
             :element-loading-text="$t('slice.loadingImg')"
             element-loading-background="rgba(0, 0, 0,0)"
        >
            <div class="psd-wrapper" ref="psdWrapper"
                 :style="{
                height:psdInfo.height + 'px',width:psdInfo.width + 'px',
                marginLeft: ( - psdInfo.width / 2 ) + 'px',
                opacity:loading ? 0 : 1
                }">

            </div>
        </div>
        
    </div>
</template>
<script>
    import {mapMutations, mapState} from "vuex"
    import i18n from "@/lang";

    let zIndex = 0
    const getAllChildNode = function (data, childrenKey) {
        let result = []

        if (Array.isArray(data)) {
            data.forEach(item => {
                item.zIndex = zIndex
                if (item[childrenKey]) {
                    zIndex += 1
                    result.push(...getAllChildNode(item[childrenKey], childrenKey))
                }
                result.push(item)
            })
        } else if (!Array.isArray(data)) {
            result.push(...getAllChildNode(data[childrenKey], childrenKey))
            result.push(data)
        }
        return result
    }

    const readJson = function (url) {
        return new Promise((resolve, reject) => {
            let xhr = new XMLHttpRequest()
            xhr.open('GET', url, true)
            xhr.send(null)
            xhr.onload = function () {
                if (xhr.status === 200) {
                    resolve({_code: 0, _success: true, _data: JSON.parse(xhr.responseText)})
                }
            }
            xhr.onerror = function () {
                resolve({_code: -1, _success: false, _data: '', _msg: i18n.t('slice.readFailed')})
            }
        })
    }

    export default {
        name: "PsdViewer",
        props: {
            viewObj: {
                type: Object,
                default() {
                    return null
                }
            }
        },
        computed: {
            ...mapState({
                downloadSlices: state => state.asset.downloadSlices,
                selectedLayer: state => state.asset.selectedLayer,
                selectedSlices: state => state.asset.selectedSlices
            }),
            selDownloadSlicesIds() {
                return (this.downloadSlices && this.downloadSlices.map(i => i.id)) || []
            }
        },
        data() {
            return {
                layers: null,
                initLayers: null,
                initPsdInfo: {},
                psdInfo: {},
                rate: 100,//缩放比例,
                tempLeft: 0,
                loading: false
            }
        },
        methods: {
            ...mapMutations('asset', ['setSelectedLayer','setAllSlices','setSelectedSlices']),

            getPsdInfo() {
                // let {M_URL, WIDTH, HEIGHT} = this.viewObj
                this.psdInfo = {
                    url: "http://192.168.50.39/api/asset/min-bucket/00001/thumbnail/7nb1OOWX/S_895f1da1-a615-4a02-80d4-5e0a53cc46ac.webp",
                    width: 300,
                    height: 200,
                }
                this.initPsdInfo = {...this.psdInfo}
            },
            handleClickLayer(slice) {
                let layer = this.initLayers.find(i => i.id === slice.id)
                //处理好url地址问题
                this.setSelectedLayer(layer)
            },
            refreshSize(e) {
                e.preventDefault && e.preventDefault()

                if (e.rate) {
                    this.rate = e.rate
                } else {
                    if (e.wheelDelta > 0) {
                        this.rate = this.rate + 5
                    } else {
                        if (this.psdInfo.width <= 300) return
                        this.rate = this.rate - 5
                    }
                }
                let rate = this.rate
                let initImgWidth = this.initPsdInfo.width
                let initImgHeight = this.initPsdInfo.height
                this.psdInfo.width = initImgWidth * rate / 100
                this.psdInfo.height = initImgHeight * rate / 100
                this.layers && this.layers.forEach(slice => {
                    let initLayer = this.initLayers.find(i => i.id === slice.id)
                    let {left, top, width, height} = initLayer
                    slice.left = left * rate / 100
                    slice.top = top * rate / 100
                    slice.width = width * rate / 100
                    slice.height = height * rate / 100
                })
            },
            onMousemove(e) {
                let el = this.$refs.psdWrapper
                this.tempLeft = this.tempLeft + e.movementX
                el.style.left = this.tempLeft + 'px'

                el.style.top = (el.offsetTop + e.movementY) + 'px'
            },
            resetSize() {
                let wrapperWidth = this.$refs.imgWrapper.offsetWidth
                let wrapperHeight = this.$refs.imgWrapper.offsetHeight
                if (wrapperHeight > wrapperWidth) {
                    if (this.psdInfo.width > wrapperWidth * 0.9) {
                        let rate = wrapperWidth * 0.9 / this.psdInfo.width * 100
                        this.refreshSize({rate})
                    }
                } else {
                    if (this.psdInfo.height > wrapperHeight * 0.9) {
                        let rate = wrapperHeight * 0.9 / this.psdInfo.height * 100
                        this.refreshSize({rate})
                    }
                }
                this.loading = false
            },
            imgError() {
                this.$message({
                    customClass: 'el-message-index',
                    type: "error",
                    message: this.$t('slice.loadingImgFailed')
                })
            }
        },
        mounted() {
            this.rate = 100
            //设置拖拽效果
            this.$nextTick(_ => {
                this.$refs.imgWrapper && this.$refs.imgWrapper.addEventListener('mousewheel', this.refreshSize)

                this.$refs.imgWrapper && this.$refs.imgWrapper.addEventListener('mousedown', (e) => {
                    e.preventDefault()
                    this.$refs.imgWrapper && this.$refs.imgWrapper.addEventListener('mousemove', this.onMousemove)
                })
                window.addEventListener('mouseup', (e) => {
                    this.$refs.imgWrapper && this.$refs.imgWrapper.removeEventListener('mousemove', this.onMousemove)
                })

                this.tempLeft = this.$refs.imgWrapper.clientWidth / 2
            })
        },
        beforeDestroy() {
            this.setSelectedLayer(null)
            this.setAllSlices(null)
            this.setSelectedSlices(null)
            this.$refs.imgWrapper && this.$refs.imgWrapper.removeEventListener('mousewheel', this.refreshSize)
        }
    }
</script>

<style lang="scss" scoped>
    .psd-viewer-root {
        width: 100%;
        height: 100%;

        .img-wrapper {
            height: 100%;
            position: relative;
            overflow: auto;

            .psd-wrapper {
                width: 100%;
                position: absolute;
                left: 50%;
                cursor: pointer;

                img {
                    width: 100%;
                    height: 100%;
                }

                .layer {
                    position: absolute;
                    cursor: pointer;

                    &:hover {
                        border: 1px solid #0092fe;
                    }

                    &.selected {
                        /*background: rgba(255, 0, 0, .4);*/
                        border: 1px solid #ff3366;
                    }

                    .icon {
                        color: #00a289;
                        font-size: 20px;
                    }

                    &.slice {
                        border: 2px dashed #ff3467;
                    }
                }
            }
        }

    }
</style>
